package com.lucker.controller;

import com.alibaba.fastjson.JSONObject;
import com.lucker.cds.model.CustomCaiPiaoOpencode;
import com.lucker.common.util.DateTimeUtil;
import com.lucker.common.util.HttpUtil;
import com.lucker.common.util.StringUtil;
import com.lucker.ds.model.CaiPiao;
import com.lucker.ds.model.CaiPiaoOpencode;
import com.lucker.ds.model.CaiType;
import com.lucker.ds.model.EvenyDayOpenTime;
import com.lucker.framework.constant.ErrorEnum;
import com.lucker.framework.constant.ResponseBaseModel;
import com.lucker.framework.exception.BaseServiceException;
import com.lucker.service.caipiao.CaiPiaoOpencodeService;
import com.lucker.service.caipiao.CaiPiaoService;
import com.lucker.service.caipiao.CaiTypeService;
import com.lucker.service.evenydayopentime.EvenyDayOpenTimeService;
import com.lucker.vo.CaiAddInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "code")
public class CaipiaoController extends BaseController {

    @Autowired
    CaiTypeService caiTypeService;

    @Autowired
    CaiPiaoService caiPiaoService;

    @Autowired
    CaiPiaoOpencodeService caiPiaoOpencodeService;

    @Autowired
    EvenyDayOpenTimeService evenyDayOpenTimeService;

    @RequestMapping(value = "/getcaitype", method = RequestMethod.GET)
    @ResponseBody
    public List<CaiType> getCaipiaoType() {
        List<CaiType> types = caiTypeService.queryAll(new CaiType());
        return types;
    }

    @RequestMapping(value = "/getcaicity", method = RequestMethod.GET)
    @ResponseBody
    public List<CaiPiao> getCaipiaoCity(@RequestParam(name = "id") String id) {
        CaiPiao caiPiao = new CaiPiao();
        caiPiao.setCaiTypeId(id);
        List<CaiPiao> caiPiaos = caiPiaoService.queryAll(caiPiao);
        return caiPiaos;
    }

    @RequestMapping(value = "/getcodelist", method = RequestMethod.GET)
    @ResponseBody
    public List<CaiPiaoOpencode> getCodeList(@RequestParam(name = "id") String caiId, @RequestParam(name = "startno") String startno, @RequestParam(name = "endno") String endno, @RequestParam(name = "order", defaultValue = "asc") String order) {
        CustomCaiPiaoOpencode _cCaiPiaoOpencode = new CustomCaiPiaoOpencode();
        _cCaiPiaoOpencode.setCaiId(caiId);
        if (StringUtil.equals("asc",order)) {
            _cCaiPiaoOpencode.orderByIssueno(true);
        } else {
            _cCaiPiaoOpencode.orderByIssueno(false);
        }

        if (StringUtils.isNotBlank(startno)) {
            _cCaiPiaoOpencode.setStartIssueno(startno);
        }
        if (StringUtils.isNotBlank(endno)) {
            _cCaiPiaoOpencode.setEndIssueno(endno);
        }
        _cCaiPiaoOpencode.setLimitEnd(3000);
        _cCaiPiaoOpencode.setLimitStart(0);
        List<CaiPiaoOpencode> _list = caiPiaoOpencodeService.getCustomMapper().selectAllByCaiId(_cCaiPiaoOpencode);
        return _list;
    }

    @RequestMapping(value = "/updatecode", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> updateCode(@RequestParam(name = "id") String id,
                                        @RequestParam(name = "opencode") String openCode,
                                        @RequestParam(name = "caiid") String caiId,
                                        @RequestParam(name = "issueno") String issueNo) {
        String[] openCodeArray = null;
        System.out.println(id+":"+openCode+":"+caiId);
        if(!StringUtils.isBlank(openCode)) {
            openCodeArray = openCode.split(",");
        }else {
            return new ResponseEntity<>(new ResponseBaseModel(29002,"提交号码为空"), HttpStatus.OK);
        }
        CaiPiaoOpencode updateCaiPiaoOpenCode = new CaiPiaoOpencode();
        updateCaiPiaoOpenCode.setId(Long.parseLong(id));
        if(openCodeArray.length > 0 && StringUtils.isNotBlank(openCodeArray[0])) {
            updateCaiPiaoOpenCode.setNumber1(openCodeArray[0]);
        }
        if(openCodeArray.length > 1 && StringUtils.isNotBlank(openCodeArray[1])) {
            updateCaiPiaoOpenCode.setNumber2(openCodeArray[1]);
        }
        if( openCodeArray.length > 2 && StringUtils.isNotBlank(openCodeArray[2])) {
            updateCaiPiaoOpenCode.setNumber3(openCodeArray[2]);
        }
        if(openCodeArray.length > 3 && StringUtils.isNotBlank(openCodeArray[3])) {
            updateCaiPiaoOpenCode.setNumber4(openCodeArray[3]);
        }
        if( openCodeArray.length > 4 && StringUtils.isNotBlank(openCodeArray[4])) {
            updateCaiPiaoOpenCode.setNumber5(openCodeArray[4]);
        }
        if(openCodeArray.length > 5 &&  StringUtils.isNotBlank(openCodeArray[5])) {
            updateCaiPiaoOpenCode.setNumber6(openCodeArray[5]);
        }
        if( openCodeArray.length > 6 && StringUtils.isNotBlank(openCodeArray[6])) {
            updateCaiPiaoOpenCode.setNumber7(openCodeArray[6]);
        }
        if(openCodeArray.length > 7 && StringUtils.isNotBlank(openCodeArray[7])) {
            updateCaiPiaoOpenCode.setNumber8(openCodeArray[7]);
        }
        try {
            caiPiaoOpencodeService.modify(updateCaiPiaoOpenCode, false);
            //改号推送通知
            Map<String,Object> params = new HashMap<>();
            params.put("caiId",caiId);
            params.put("issueno",issueNo);
            HttpUtil.get("http://120.27.224.207:8280/lucker-api/caipiao/update_push_opencode",params);
//            CaiPiaoOpencode updateCode = new CaiPiaoOpencode();
//            updateCode.setCaiId(caiId);
//            updateCode.setIssueno(issueNo);
//            return caiPiaoService.update_push_opencode(updateCode);
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(new ResponseBaseModel(29002,"更新失败"), HttpStatus.OK);
        }
    }


    /**
     * 删除开奖记录
     * @param id
     * @return
     */
    @RequestMapping(value = "/deletecode", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> deleteCode(@RequestParam(name = "id") String id){
        try {
            if(StringUtils.isBlank(id)) {
                return new ResponseEntity<>(new ResponseBaseModel(29002,"参数id 不能为空"), HttpStatus.OK);
            }
            caiPiaoOpencodeService.remove(Long.parseLong(id));
            return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
        }catch (Exception e){
            return new ResponseEntity<>(new ResponseBaseModel(29002,"删除失败"), HttpStatus.OK);
        }
    }

    /**
     * 手动添加号码
     * @param info
     * @return
     */
    @RequestMapping(value="/addopencode",method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<?> addOpencode(@RequestBody CaiAddInfo info) {
        try {
            if(StringUtils.isBlank(info.getCaiId())) {
                return new ResponseEntity<>(new ResponseBaseModel(29002,"参数cai_id 不能为空"), HttpStatus.OK);
            }
            if(info.getIssueNo() == null && info.getIssueNo().length() < 8) {
                return new ResponseEntity<>(new ResponseBaseModel(29002,"期号为空，或期号长度错误! "), HttpStatus.OK);
            }
            getLoger().error("提交的数据为: " + JSONObject.toJSONString(info));

            EvenyDayOpenTime queryEvenyDayOpenTime = new EvenyDayOpenTime();
            queryEvenyDayOpenTime.setCaiId(Long.valueOf(info.getCaiId()));
            queryEvenyDayOpenTime.setIssueno(info.getIssueNo());
            List<EvenyDayOpenTime> evenyDayOpenTimeList = evenyDayOpenTimeService.queryAll(queryEvenyDayOpenTime);
            if(CollectionUtils.isEmpty(evenyDayOpenTimeList)) {
                throw new BaseServiceException("该cai_id : " +info.getCaiId()+" , 对应的该期号 : "+ info.getIssueNo() +"  在 eveny_day_open_time 表中没有记录,请联系系统管理员进行维护");
            }

            if(evenyDayOpenTimeList.size() > 1) {
                throw new BaseServiceException("该cai_id : " +info.getCaiId()+" , 对应的该期号 : "+ info.getIssueNo() +"  在 eveny_day_open_time 表中存在多条记录,请联系系统管理员进行维护");
            }

            String caipiaoOpenTimeStr = DateTimeUtil.getDate(evenyDayOpenTimeList.get(0).getOpenDate(), DateTimeUtil.FORMAT_LONGTIME);
            Map<String,Object> _map = new HashMap<>();
            _map.put("openCode", info.getOpenCode());   //开奖号码
            _map.put("issueNo", info.getIssueNo());  //期号，一定是八位的这种格式
            _map.put("caiId", info.getCaiId()); //彩种ID
            _map.put("commitTime", info.getCommitTime());  //提交时间
            _map.put("openTime", caipiaoOpenTimeStr);   //开奖时间
            HttpUtil.get("http://120.27.224.207:8280/lucker-api/caipiao/missCodeCommit",_map);
//            caiPiaoService.commitCaiPiao(info.getOpenCode(), "手动补号", info.getIssueNo(),info.getCommitTime(), info.getCaiId());
            return new ResponseEntity<>(new ResponseBaseModel(10000,"ok"), HttpStatus.OK);
        }catch(Exception e) {
            this.getLoger().error("提交异常 {} , {}", e.getMessage(),e);
            return new ResponseEntity<>(new ResponseBaseModel(29002,e.getMessage()), HttpStatus.OK);
        }
    }
}
